/**
    GpsNetwork lets you download files and log some system parameters from NetRs DGPS receivers.

    Copyright (C) 2009  Eduardo Maureira

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    email:emaureir@gmail.com
 */
package netrs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;

public class ClienteHttp {

	private URL url;
	/**
	 * Consulta a ejecutarse en el dispositivo
	 */
	private String resource;

	private String protocol;
	private String host;
	private int port;
	private String username;
	private String password;

	private static final Logger logger = Logger.getLogger(ClienteHttp.class);

	/**
	 * Crea un cliente http capaz de consultar distintas urls sobre el mismo host
	 * @param protocol
	 * @param host
	 * @param port
	 * @param username
	 * @param Password
	 */
	public ClienteHttp(String protocol, String host, int port,String username,String Password) {
		super();
		this.host = host;
		this.port = port;
		this.protocol = protocol;
		this.username = username;
		this.password = Password;
		StringBuilder mensaje;
		mensaje = new StringBuilder();
		mensaje.append("nuevo ClienteHttp-->");
		mensaje.append(protocol);
		mensaje.append("://");
		mensaje.append(host);
		mensaje.append(":");
		mensaje.append(port);

		logger.info(mensaje.toString());
	}

	/**
	 * Kernel del proyecto, aqui se generan las consultas http al GPS (host)
	 * y se obtienen las respuestas en cadenas de texto
	 * @return Respuesta del Host
	 */
	public String txtRequest ()
	{
		String respuesta;
		StringBuilder strbRespuesta;
		StringBuilder userpass;
		BufferedReader in;
		URLConnection conn;
		in = null;
		strbRespuesta = new StringBuilder();
		respuesta = null;
		try {

			url = new URL(this.protocol,this.host,this.port,resource);
			try {
				conn = url.openConnection();
				conn.setReadTimeout(Config.getHttpTimeOut());
				userpass = new StringBuilder();
				userpass.append(this.username);
				userpass.append(":");
				userpass.append(this.password);

				String encoding = new sun.misc.BASE64Encoder().encode(userpass.toString().getBytes());
				conn.setRequestProperty ("Authorization", "Basic " + encoding);
				in = new BufferedReader(
						new InputStreamReader(
								conn.getInputStream()));
			} catch (IOException e) {
				logger.error("Error al conectar con url->"+url.toString());
				return null;
			}

			String inputLine;

			try {
				while ((inputLine = in.readLine()) != null)
				{
					strbRespuesta.append(inputLine);
					strbRespuesta.append(" ");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


		} catch (MalformedURLException e) {

			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (strbRespuesta.length()>0)
		{
			respuesta = strbRespuesta.toString();
		}
		return respuesta;
	}	

	//	public URL getUrl() {
	//		return url;
	//	}
	//
	//	public void setUrl(URL url) {
	//		this.url = url;
	//	}

	/**
	 * 
	 * @return Consulta a ejecutarse en el dispositivo
	 */
	public String getResource() {
		return resource;
	}

	/**
	 * Util para obtener listas de archivos o directorios
	 * @param resource Cadena de texto con la lista consultada
	 */
	public void setResource(String resource) {
		this.resource = resource;
		try {
			url = new URL(this.protocol,this.host,this.port,resource);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



	public String getProtocol() {
		return protocol;
	}

	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public URL getUrl() {
		return url;
	}

	public void setUrl(URL url) {
		this.url = url;
	}


	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}



	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ClienteHttp test;
		//test = new ClienteHttp("http","gps.cetecfiuls.cl",80);
		test = new ClienteHttp("http","172.17.71.180",80,"sysadmin","rsnet");
		//test.setResource("/prog/Show?LoggedFiles&directory=/");
		test.setResource("/prog/Show?SystemName");
		String respuesta;
		respuesta = test.txtRequest();
		System.out.println("respuesta="+respuesta);
	}
}
